package com.cskaoyan.service;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.bean.baseresultVO.BaseData;
import com.cskaoyan.bean.baseresultVO.BaseParam;
import com.cskaoyan.bean.domain.*;
import com.cskaoyan.bean.order.Chanal.Chanal;
import com.cskaoyan.bean.order.baseorders.BaseOrder.BaseOrder;
import com.cskaoyan.bean.order.baseorders.BaseOrder.OrderShowType;
import com.cskaoyan.bean.order.ordership.OrderShioBo;
import com.cskaoyan.bean.order.wxGetOrder.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.MyUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.power.common.util.RandomUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yaml.snakeyaml.events.Event;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.System;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author looper
 * @since 2021-11-29
 */
@Transactional
@Service
public class OrderServiceImpl implements OrderService {


    @Resource
    OrderMapper mapper;

    //订单回显需要
    @Resource
    UserMapper userMapper;

    @Resource
    OrderGoodsMapper orderGoodsMapper;

    @Resource
    CommentMapper commentMapper;

    @Resource
    AddressMapper addressMapper;

    @Resource
    CartMapper cartMapper;

    @Resource
    CouponUserMapper couponUserMapper;

    @Resource
    CouponMapper couponMapper;


    @Override
    public List<Chanal> getChanel() {
        //查询所有快递公司 所有delete为0的
        List<Chanal> list = mapper.selectAllChanel();

        return list;
    }

    @Override
    public BaseData getOrderList(BaseParam baseParam, Order order,
                                 String[] orderStatusArray,
                                 Date start, Date end) {
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        ArrayList<Short> shorts = new ArrayList<>();
        //将orderStatusArray状态用in查询,转换为shorts集合
        if (orderStatusArray != null) {
            for (String s : orderStatusArray) {
                Short aShort = Short.valueOf(s);
                shorts.add(aShort);
            }
        }
        //查询userid是eq,订单编号是like,订单时间在二者之间,订单状态用查询之后的筛选
        OrderExample example = new OrderExample();
        //order不为空说明有userid与ordersn orderid是另外一个请求
        OrderExample.Criteria criteria = example.createCriteria();

        if (order.getUserId() != null) {
            criteria.andUserIdEqualTo(order.getUserId());
        }
        if (!MyUtils.isEmpty(order.getOrderSn())) {
            criteria.andOrderSnLike(order.getOrderSn());
        }
        if (orderStatusArray != null && start != null) {
            //两个条件都为空时拼接两个条件
            criteria.andOrderStatusIn(shorts).andAddTimeGreaterThanOrEqualTo(start).andEndTimeLessThanOrEqualTo(end);
        } else {
            if (orderStatusArray != null) {
                //单个条件为空拼接一个
                criteria.andOrderStatusIn(shorts);
            }
            if (start != null || end != null) {
                //单个条件为空拼接一个
                criteria.andAddTimeGreaterThanOrEqualTo(start).andEndTimeLessThanOrEqualTo(end);
            }
        }
        //处理逻辑删除
        criteria.andDeletedEqualTo(false);
        //排序
        example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());

        List<Order> orders = mapper.selectByExample(example);
        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        //分页的信息
        //将total变为int类型
        Integer total = MyUtils.getInteger(orderPageInfo.getTotal());
        return BaseData.getBack(baseParam.getLimit(), baseParam.getPage(), orderPageInfo.getPages(), total, orders);
    }


    @Override
    public BaseOrder getOrderDetail(Integer id) {
        //order信息
        Order order = mapper.selectByPrimaryKey(id);
        OrderGoodsExample goodsExample = new OrderGoodsExample();
        //ordergoods的信息
        goodsExample.createCriteria().andOrderIdEqualTo(id);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(goodsExample);
        //查询出id为订单userid的user信息
        User user = userMapper.selectByPrimaryKey(order.getUserId());
        //封装进Vo中
        BaseOrder baseOrder = new BaseOrder();
        baseOrder.setOrder(order);
        baseOrder.setOrderGoods(orderGoods);
        baseOrder.setUser(user);
        return baseOrder;
    }

    @Override
    public Integer deleteByUpdate(Integer orderId) {
        Date date = new Date();
        //逻辑删除并且更新时间
        mapper.deleteByUpdate(orderId, date);

        return 200;

    }

    @Override
    public Integer getShip(OrderShioBo orderShioBo) {
        //根据orderid 也就是order的id 修改快递信息:快递名字√  快递单号√ 订单状态301 增加修改时间
        Order order = new Order();
        order.setShipChannel(orderShioBo.getShipChannel());
        order.setShipSn(orderShioBo.getShipSn());
        //301表示已发货
        order.setOrderStatus(Short.valueOf("301"));
//        order.setAddTime(LocalDateTime.now());
        //拼接条件
        OrderExample example = new OrderExample();
        example.createCriteria().andIdEqualTo(orderShioBo.getOrderId());
        mapper.updateByExampleSelective(order, example);
        return 200;

    }

    @Override
    public BaseData getOrderListForUser(OrderShowType ordershowType, BaseParam baseParam, User user) {
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        //根据showtype查询订单
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        if (0 == ordershowType.getShowType()) {
            //查询全部
        }
        if (1 == ordershowType.getShowType()) {
            //1=代付款 查询订单状态为101的
            criteria.andOrderStatusEqualTo(Short.valueOf("101"));
        }
        if (2 == ordershowType.getShowType()) {
            //2=代发货 查询订单状态为201的
            criteria.andOrderStatusEqualTo(Short.valueOf("201"));
        }
        if (3 == ordershowType.getShowType()) {
            //3=代收货 查询订单状态为301的
            criteria.andOrderStatusEqualTo(Short.valueOf("301"));
        }
        if (4 == ordershowType.getShowType()) {
            List<Short> shortList = new ArrayList<>();
            shortList.add(Short.valueOf("401"));
            shortList.add(Short.valueOf("402"));
            //4=已经收货 查询订单状态为401与402的
            criteria.andOrderStatusIn(shortList);
        }
        //锁定为当前用户id的订单
        criteria.andUserIdEqualTo(user.getId()).andDeletedEqualTo(false);
        //排序
        if (!MyUtils.isEmpty(baseParam.getOrder()) && !MyUtils.isEmpty(baseParam.getSort())) {
            orderExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        }
        List<Order> orders = mapper.selectByExample(orderExample);

        // TODO: 2021/12/5
        //遍历所有订单,拿到add时间,加上配置文件的时间 如果小于当前时间->改状态103

        expire(orders);


        ArrayList<OrderList> orderLists = new ArrayList<>();
        //将查询结果传递给Orderlist 满足返回值的StatusText
        for (Order order : orders) {
            OrderList orderList = new OrderList();
            BeanUtils.copyProperties(order, orderList);
            orderLists.add(orderList);
        }
        // TODO: 2021/12/2 之后要对 orderLists 进行遍历把每一个goodslist和handleOption放进去
        for (int i = 0; i < orderLists.size(); i++) {
            //对每一个orderVo的goodslist与handleOption赋值
            OrderList orderVo = orderLists.get(i);
            OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
            //返回所有订单商品表的orderid等于当前订单id的商品列表
            orderGoodsExample.createCriteria().andOrderIdEqualTo(orderVo.getId()).andDeletedEqualTo(false);
            List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
            orderVo.setGoodsList(orderGoods);
            //之后填充handleOption 根据订单id查询,之后转换给handleoption
            Integer id = orderVo.getId();
            Order order = mapper.selectByPrimaryKey(id);
            HandleOption handleOption = new HandleOption();
            BeanUtils.copyProperties(order, handleOption);
            orderVo.setHandleOption(handleOption);
        }
        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        return BaseData.getBack(orderPageInfo.getSize(), orderPageInfo.getPageNum(), orderPageInfo.getPages(),
                MyUtils.getInteger(orderPageInfo.getTotal()), orderLists);


    }

    // TODO: 2021/12/5
    //遍历所有订单,拿到add时间,加上配置文件的时间 如果小于当前时间->改状态103

    private void expire(List<Order> orders) {
        Properties properties = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(new File("src/main/resources/config.properties"));
            properties = new Properties();
            properties.load(fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object market_order_unpaid = properties.get("market_order_unpaid");
        Integer expireMin = Integer.parseInt((String) market_order_unpaid);

        for (Order order : orders) {
            LocalDateTime addTime = order.getAddTime();
            long addSecond = addTime.toEpochSecond(ZoneOffset.of("+8"));
            long nowSecond = new Date().getTime() / 1000;
            if (order.getOrderStatus()==101&&MyUtils.getInteger(addSecond) + expireMin < MyUtils.getInteger(nowSecond)) {
                //条件
                Integer id = order.getId();
                OrderExample orderExample = new OrderExample();
                orderExample.createCriteria().andIdEqualTo(id);
                //
                order.setOrderStatus((short) 103);
                mapper.updateByExampleSelective(order, orderExample);
            }


        }


    }

    @Override
    public OrderDetailForUser getOrderdetailForUser(Order order) {
        Integer id = order.getId();
        //根据order的id查询信息 ->查询对应ordergoods表对应orderid的商品集合
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(id);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        //放入vo
        OrderDetailForUser orderDetailForUser = new OrderDetailForUser();
        orderDetailForUser.setOrderGoods(orderGoods);
        //查询orderinfo
        Order orderInfoPOJO = mapper.selectByPrimaryKey(id);
        //传递参数
        OrderList orderList = new OrderList();
        BeanUtils.copyProperties(orderInfoPOJO, orderList);
        //传递参数给handleOption
        HandleOption handleOption = new HandleOption();
        BeanUtils.copyProperties(orderInfoPOJO, handleOption);
        //set
        orderList.setHandleOption(handleOption);

        //把得到的orderList(已经封装好了handleOption)放入Vo
        OrderExpName orderExpName = new OrderExpName();
        //利用beanUtils给快递名字与帐号赋值
        BeanUtils.copyProperties(orderList, orderExpName);
        orderDetailForUser.setOrderInfo(orderExpName);
        return orderDetailForUser;

    }

    @Override
    public Integer getChangeStatus(Order order) {
        Integer id = order.getId();
        order.setId(null);
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(id).andDeletedEqualTo(false);
        order.setAddTime(null);
        //order里只有status信息
        mapper.updateByExampleSelective(order, orderExample);
        return 200;

    }


    @Override
    public Integer getComment(Comment comment, Integer orderGoodsId) {
        if (orderGoodsId != null) {
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setUpdateTime(new Date());
            OrderGoodsExample orderGoodsExample = new OrderGoodsExample();

            System.out.println(orderGoodsId+"=====================");

            orderGoodsExample.createCriteria().andIdEqualTo(orderGoodsId);
            //更新orderGoods表中的更新时间
            orderGoodsMapper.updateByExampleSelective(orderGoods, orderGoodsExample);
            //从表中查询出购买商品的id,加入评论
            OrderGoods orderGoodsPOJO = orderGoodsMapper.selectByPrimaryKey(orderGoodsId);
            String goodsSn = orderGoodsPOJO.getGoodsSn();

            System.out.println(goodsSn+"===========================");

            comment.setValueId(Integer.parseInt(goodsSn));
            //查出对应的订单id
            Integer orderId = orderGoodsPOJO.getOrderId();
            //先查出评论数
            Order orderKey = mapper.selectByPrimaryKey(orderId);
            Short comments = orderKey.getComments();
            Integer anInt = Integer.parseInt(comments.toString());
            anInt = anInt - 1;
            //对这个订单评论数减少1 更新时间更新
            //完成评论,order表中的评论数减1
            Order order = new Order();
            order.setComments(Short.valueOf(anInt.toString()));
            order.setUpdateTime(LocalDateTime.now());
            OrderExample orderExample = new OrderExample();
            orderExample.createCriteria().andIdEqualTo(orderId);
            mapper.updateByExampleSelective(order, orderExample);

        }
        comment.setUpdateTime(new Date());
        comment.setAddTime(new Date());
        comment.setType(Byte.valueOf("0"));
        commentMapper.insertSelective(comment);
        return 200;

    }

    @Override
    public List<OrderGoods> getGoods(OrderGoods orderGoods) {

        OrderGoodsExample orderExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderExample.createCriteria();
        criteria.andOrderIdEqualTo(orderGoods.getOrderId());
        criteria.andGoodsIdEqualTo(orderGoods.getGoodsId());
        //
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderExample);
        return orderGoodsList;

    }

    @Override
    public Integer orderSubmit(WxOrderBO order) {
        //根据addressId查询到address_detail，即用户收货地址
        //根据cartId获取到商品信息，如果cartId不为0，就是单个商品的下单，如果为0，就是购物车商品下单
        //如果是直接单个商品下单，需将购物车表的对应id的delete变为true，如果不是0，查询该用户购物车checked为true的商品
        //插入order表后返回orderId，并且将上边的商品信息插入到orderGoods表里

        //获取用户信息
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipals().getPrimaryPrincipal();
        //根据id拿到address信息
        Address address = addressMapper.selectByPrimaryKey(order.getAddressId());
        //根据cartId拿到cart信息
        List<Cart> cartList = new ArrayList<>();
        if (order.getCartId() != 0) {
            //直接单品下单
            Cart cart = cartMapper.selectByPrimaryKey(order.getCartId());
            cartList.add(cart);
        } else {
            //购物车下单
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andCheckedEqualTo(true).andUserIdEqualTo(user.getId()).andDeletedEqualTo(false);
            cartList = cartMapper.selectByExample(cartExample);
        }
        //将cartList里的记录的deleted置为true
        for (Cart cart : cartList) {
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andIdEqualTo(cart.getId());
            cartMapper.updateByExampleSelective(cart, cartExample);
        }
        //根据couponId和userCouponId以及userId更改用户优惠券的使用状态，感觉一个userCouponId就可以
        CouponUserExample couponUserExample = new CouponUserExample();
        couponUserExample.createCriteria();
        CouponUser couponUser = new CouponUser();
        couponUser.setId(order.getUserCouponId());
        couponUser.setStatus((short) 1);
        couponUserMapper.updateByPrimaryKeySelective(couponUser);

        //获取配送费用
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(new File("src/main/resources/config.properties")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object express_freight_min = properties.get("market_express_freight_min");
        Object express_freight_value = properties.get("market_express_freight_value");
        //低消
        BigDecimal min_freight = new BigDecimal(String.valueOf(express_freight_min));
        //运费
        BigDecimal freight_value = new BigDecimal(String.valueOf(express_freight_value));

        //根据couponId查询优惠金额
        Coupon coupon = couponMapper.selectByPrimaryKey(order.getCouponId());

        //开始插入order表
        Order order1 = new Order();
        order1.setUserId(user.getId());
        String order_sn = RandomUtil.randomString(3);
        order1.setOrderSn(order_sn);
        order1.setOrderStatus((short) 101);
        order1.setConsignee(address.getName());
        order1.setMobile(address.getTel());
        order1.setAddress(address.getAddressDetail());
        order1.setMessage(order.getMessage());
        order1.setCouponPrice(coupon.getDiscount());
        //商品总费用
        BigDecimal sumAmount = new BigDecimal("0");
        for (Cart cart : cartList) {
            Short number = cart.getNumber();
            //商品总价=单价*数量
            BigDecimal price = cart.getPrice().multiply(new BigDecimal(String.valueOf(number)));
            sumAmount = sumAmount.add(price);
            //todo
            System.out.println(price);
        }
        order1.setGoodsPrice(sumAmount);
        //如果商品总价比低消多,就取消运费,否则不取消运费
        if (sumAmount.compareTo(min_freight) >= 0)
            freight_value = new BigDecimal("0");
        //设置运费
        order1.setFreightPrice(freight_value);
        //加上运费后的商品总价
        BigDecimal price = sumAmount.add(freight_value).subtract(coupon.getDiscount());
        order1.setOrderPrice(price);
        //减去优惠券的实际总价
        order1.setActualPrice(price);
        order1.setPayTime(LocalDateTime.now());
        order1.setShipSn(RandomUtil.randomString(8));
        order1.setAddTime(LocalDateTime.now());
        order1.setIntegralPrice(new BigDecimal("0"));
        order1.setGrouponPrice(new BigDecimal("0"));
        order1.setPayId(RandomUtil.randomString(8));
        //插入订单表,获取订单id
        mapper.insertSelective(order1);

        //遍历购物车，插入orderGoods表
        for (Cart cart : cartList) {
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderId(order1.getId());
            orderGoods.setGoodsId(cart.getGoodsId());
            orderGoods.setGoodsName(cart.getGoodsName());
            orderGoods.setGoodsSn(cart.getGoodsSn());
            orderGoods.setProductId(cart.getProductId());
            orderGoods.setNumber(cart.getNumber());
            orderGoods.setPrice(cart.getPrice());
            orderGoods.setSpecifications(cart.getSpecifications());
            orderGoods.setPicUrl(cart.getPicUrl());
            orderGoods.setAddTime(new Date());
            orderGoods.setUpdateTime(new Date());
            orderGoodsMapper.insertSelective(orderGoods);
            Cart cart1 = new Cart();
            cart1.setId(cart.getId());
            cart1.setDeleted(true);
            cartMapper.updateByPrimaryKeySelective(cart1);
        }


        return order1.getId();
    }


}

